/**
 * Appointment Form Module
 * Handles appointment creation, editing, and detail forms
 */
const AppointmentForm = (function() {
    // Form state
    let state = {
        doctors: [],
        selectedDoctor: null,
        selectedDate: null,
        selectedTimeSlot: null,
        appointmentTypes: {
            REGULAR: '常规问诊',
            FOLLOW_UP: '复诊',
            CONSULTATION: '专家会诊',
            PHYSICAL: '体检预约',
            EMERGENCY: '紧急预约'
        },
        currentStep: 1,
        totalSteps: 3,
        formMode: 'create', // 'create', 'edit', 'view'
        currentAppointment: null
    };
    
    /**
     * Render the appointment creation form
     */
    function renderCreateForm(modalBody, selectedDate) {
        state.selectedDate = selectedDate || new Date();
        state.currentStep = 1;
        state.formMode = 'create';
        
        modalBody.innerHTML = `
            <div class="form-stepper">
                <div class="step active" data-step="1">
                    <div class="step-number">1</div>
                    <div class="step-label">选择医生</div>
                </div>
                <div class="step" data-step="2">
                    <div class="step-number">2</div>
                    <div class="step-label">选择时间</div>
                </div>
                <div class="step" data-step="3">
                    <div class="step-number">3</div>
                    <div class="step-label">确认信息</div>
                </div>
            </div>
            
            <div class="step-content" id="step-1-content">
                <h4>选择医生</h4>
                <div class="search-container">
                    <input type="text" id="doctor-search" class="form-control" placeholder="搜索医生姓名或专业...">
                    <div class="filter-container">
                        <select id="specialty-filter" class="form-control">
                            <option value="">全部专科</option>
                            <option value="内科">内科</option>
                            <option value="外科">外科</option>
                            <option value="心脏科">心脏科</option>
                            <option value="神经科">神经科</option>
                            <option value="骨科">骨科</option>
                            <option value="妇产科">妇产科</option>
                            <option value="儿科">儿科</option>
                            <option value="眼科">眼科</option>
                            <option value="口腔科">口腔科</option>
                        </select>
                    </div>
                </div>
                <div class="doctor-selection" id="doctor-selection">
                    <div class="loading-spinner">
                        <i class="fas fa-spinner fa-spin"></i>
                        <span>加载医生列表...</span>
                    </div>
                </div>
            </div>
            
            <div class="step-content" id="step-2-content" style="display:none;">
                <h4>选择预约时间</h4>
                <div class="appointment-date-select">
                    <div class="date-selector">
                        <label>预约日期</label>
                        <div class="date-picker-container">
                            <input type="date" id="appointment-date" class="form-control">
                        </div>
                    </div>
                    <div class="appointment-type-select">
                        <label>预约类型</label>
                        <select id="appointment-type" class="form-control">
                            <option value="REGULAR">常规问诊</option>
                            <option value="FOLLOW_UP">复诊</option>
                            <option value="CONSULTATION">专家会诊</option>
                            <option value="PHYSICAL">体检预约</option>
                            <option value="EMERGENCY">紧急预约</option>
                        </select>
                    </div>
                </div>
                <div class="time-slots-container">
                    <h5>可用时间段</h5>
                    <div class="time-slot-selection" id="time-slot-selection">
                        <div class="loading-spinner">
                            <i class="fas fa-spinner fa-spin"></i>
                            <span>加载可用时间...</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="step-content" id="step-3-content" style="display:none;">
                <h4>确认预约信息</h4>
                <div class="appointment-summary">
                    <div class="summary-section">
                        <h5>医生信息</h5>
                        <div class="doctor-summary" id="summary-doctor-info">
                            <!-- Will be filled dynamically -->
                        </div>
                    </div>
                    <div class="summary-section">
                        <h5>预约详情</h5>
                        <div class="appointment-details-summary">
                            <div class="detail-row">
                                <span class="detail-label">预约日期</span>
                                <span class="detail-value" id="summary-date"></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">预约时间</span>
                                <span class="detail-value" id="summary-time"></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">预约类型</span>
                                <span class="detail-value" id="summary-type"></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">预计时长</span>
                                <span class="detail-value" id="summary-duration"></span>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>预约原因 / 症状描述</label>
                        <textarea id="appointment-notes" class="form-control" placeholder="请简要描述您的症状或预约原因..."></textarea>
                    </div>
                    <div class="form-group">
                        <label>预约地点</label>
                        <select id="appointment-location" class="form-control">
                            <option value="线上问诊">线上问诊</option>
                            <option value="门诊楼1楼内科诊室">门诊楼1楼内科诊室</option>
                            <option value="门诊楼2楼外科诊室">门诊楼2楼外科诊室</option>
                            <option value="门诊楼3楼专家诊室">门诊楼3楼专家诊室</option>
                            <option value="体检中心">体检中心</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="modal-footer">
                <button id="prev-step" class="btn btn-secondary" style="display:none;">上一步</button>
                <button id="next-step" class="btn btn-primary">下一步</button>
                <button id="submit-appointment" class="btn btn-success" style="display:none;">确认预约</button>
            </div>
        `;
        
        // Set the default date to the selected date
        const datePicker = document.getElementById('appointment-date');
        if (datePicker && state.selectedDate) {
            const formattedDate = state.selectedDate.toISOString().split('T')[0];
            datePicker.value = formattedDate;
            datePicker.min = new Date().toISOString().split('T')[0]; // Cannot select past dates
        }
        
        // Set up event listeners for the form navigation
        setupFormNavigation();
        
        // Load doctors data
        loadDoctorsForSelection();
    }
    
    /**
     * Setup form navigation (next/prev buttons)
     */
    function setupFormNavigation() {
        const nextBtn = document.getElementById('next-step');
        const prevBtn = document.getElementById('prev-step');
        const submitBtn = document.getElementById('submit-appointment');
        
        if (nextBtn) {
            nextBtn.addEventListener('click', () => {
                if (validateCurrentStep()) {
                    goToNextStep();
                }
            });
        }
        
        if (prevBtn) {
            prevBtn.addEventListener('click', () => {
                goToPrevStep();
            });
        }
        
        if (submitBtn) {
            submitBtn.addEventListener('click', () => {
                submitAppointment();
            });
        }
    }
    
    /**
     * Validate the current step before proceeding
     */
    function validateCurrentStep() {
        if (state.currentStep === 1) {
            if (!state.selectedDoctor) {
                showValidationError('请选择一位医生');
                return false;
            }
        } else if (state.currentStep === 2) {
            if (!document.getElementById('appointment-date').value) {
                showValidationError('请选择预约日期');
                return false;
            }
            
            if (!state.selectedTimeSlot) {
                showValidationError('请选择预约时间段');
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * Show a validation error
     */
    function showValidationError(message) {
        // You could implement a toast notification or alert here
        alert(message);
    }
    
    /**
     * Go to the next step in the form
     */
    function goToNextStep() {
        if (state.currentStep < state.totalSteps) {
            // Hide current step content
            document.getElementById(`step-${state.currentStep}-content`).style.display = 'none';
            
            // If moving from step 2 to 3, update the summary
            if (state.currentStep === 2) {
                updateAppointmentSummary();
            }
            
            // Increment step
            state.currentStep++;
            
            // Show next step content
            document.getElementById(`step-${state.currentStep}-content`).style.display = 'block';
            
            // Update stepper UI
            updateStepperUI();
            
            // Update navigation buttons
            updateNavigationButtons();
        }
    }
    
    /**
     * Go to the previous step in the form
     */
    function goToPrevStep() {
        if (state.currentStep > 1) {
            // Hide current step content
            document.getElementById(`step-${state.currentStep}-content`).style.display = 'none';
            
            // Decrement step
            state.currentStep--;
            
            // Show previous step content
            document.getElementById(`step-${state.currentStep}-content`).style.display = 'block';
            
            // Update stepper UI
            updateStepperUI();
            
            // Update navigation buttons
            updateNavigationButtons();
        }
    }
    
    /**
     * Update the stepper UI based on current step
     */
    function updateStepperUI() {
        // Remove active class from all steps
        document.querySelectorAll('.step').forEach(step => {
            step.classList.remove('active');
            step.classList.remove('completed');
        });
        
        // Add appropriate classes to steps
        for (let i = 1; i <= state.totalSteps; i++) {
            const stepElem = document.querySelector(`.step[data-step="${i}"]`);
            if (i < state.currentStep) {
                stepElem.classList.add('completed');
            } else if (i === state.currentStep) {
                stepElem.classList.add('active');
            }
        }
    }
    
    /**
     * Update navigation buttons based on current step
     */
    function updateNavigationButtons() {
        const prevBtn = document.getElementById('prev-step');
        const nextBtn = document.getElementById('next-step');
        const submitBtn = document.getElementById('submit-appointment');
        
        if (state.currentStep === 1) {
            prevBtn.style.display = 'none';
            nextBtn.style.display = 'block';
            submitBtn.style.display = 'none';
        } else if (state.currentStep === state.totalSteps) {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'none';
            submitBtn.style.display = 'block';
        } else {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            submitBtn.style.display = 'none';
        }
    }
    
    /**
     * Load doctors for selection
     */
    function loadDoctorsForSelection() {
        const doctorSelection = document.getElementById('doctor-selection');
        if (!doctorSelection) return;
        
        // In a real app, this would be an API call
        // For now, we'll use mock data
        const mockDoctors = getMockDoctors();
        state.doctors = mockDoctors;
        
        // Clear loading spinner
        doctorSelection.innerHTML = '';
        
        // Create doctor cards
        mockDoctors.forEach(doctor => {
            const doctorCard = createDoctorCard(doctor);
            doctorSelection.appendChild(doctorCard);
        });
        
        // Add search functionality
        setupDoctorSearch();
    }
    
    /**
     * Create a doctor card for selection
     */
    function createDoctorCard(doctor) {
        const card = document.createElement('div');
        card.className = 'doctor-card';
        card.dataset.id = doctor.id;
        
        card.innerHTML = `
            <div class="doctor-card-header">
                <img src="${doctor.avatar}" alt="${doctor.name}">
                <h4>${doctor.name}</h4>
                <p>${doctor.specialty}</p>
            </div>
            <div class="doctor-card-body">
                <div class="info-row">
                    <span class="info-label">医院</span>
                    <span class="info-value">${doctor.hospital}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">评分</span>
                    <span class="info-value">${doctor.rating} <i class="fas fa-star" style="color: gold;"></i></span>
                </div>
                <div class="info-row">
                    <span class="info-label">经验</span>
                    <span class="info-value">${doctor.experience}</span>
                </div>
            </div>
        `;
        
        // Add click event to select doctor
        card.addEventListener('click', () => {
            // Deselect any previously selected doctor
            document.querySelectorAll('.doctor-card.selected').forEach(card => {
                card.classList.remove('selected');
            });
            
            // Select this doctor
            card.classList.add('selected');
            state.selectedDoctor = doctor;
        });
        
        return card;
    }
    
    /**
     * Set up the doctor search and filter functionality
     */
    function setupDoctorSearch() {
        const searchInput = document.getElementById('doctor-search');
        const specialtyFilter = document.getElementById('specialty-filter');
        
        if (searchInput) {
            searchInput.addEventListener('input', filterDoctors);
        }
        
        if (specialtyFilter) {
            specialtyFilter.addEventListener('change', filterDoctors);
        }
    }
    
    /**
     * Filter doctors based on search and specialty filter
     */
    function filterDoctors() {
        const searchInput = document.getElementById('doctor-search');
        const specialtyFilter = document.getElementById('specialty-filter');
        const doctorCards = document.querySelectorAll('.doctor-card');
        
        const searchTerm = searchInput?.value.toLowerCase() || '';
        const specialty = specialtyFilter?.value || '';
        
        doctorCards.forEach(card => {
            const doctorId = card.dataset.id;
            const doctor = state.doctors.find(d => d.id.toString() === doctorId);
            
            if (!doctor) return;
            
            const matchesSearch = doctor.name.toLowerCase().includes(searchTerm) || 
                                 doctor.specialty.toLowerCase().includes(searchTerm);
            const matchesSpecialty = !specialty || doctor.specialty === specialty;
            
            if (matchesSearch && matchesSpecialty) {
                card.style.display = 'block';
            } else {
                card.style.display = 'none';
            }
        });
    }
    
    /**
     * Load time slots for the selected date and doctor
     */
    function loadTimeSlots() {
        const timeSlotsContainer = document.getElementById('time-slot-selection');
        const datePicker = document.getElementById('appointment-date');
        
        if (!timeSlotsContainer || !datePicker || !state.selectedDoctor) return;
        
        const selectedDate = datePicker.value;
        
        // In a real app, this would be an API call with the selected date and doctor
        // For now, we'll generate some mock time slots
        const mockTimeSlots = generateMockTimeSlots(selectedDate);
        
        // Clear loading spinner
        timeSlotsContainer.innerHTML = '';
        
        // Create time slot elements
        mockTimeSlots.forEach(slot => {
            const timeSlot = document.createElement('div');
            timeSlot.className = `time-slot ${slot.available ? '' : 'unavailable'}`;
            timeSlot.textContent = slot.time;
            timeSlot.dataset.time = slot.time;
            
            // Add click event only if the slot is available
            if (slot.available) {
                timeSlot.addEventListener('click', () => {
                    // Deselect any previously selected time slot
                    document.querySelectorAll('.time-slot.selected').forEach(slot => {
                        slot.classList.remove('selected');
                    });
                    
                    // Select this time slot
                    timeSlot.classList.add('selected');
                    state.selectedTimeSlot = slot;
                });
            }
            
            timeSlotsContainer.appendChild(timeSlot);
        });
        
        // If we had a previously selected time slot, try to select it again
        if (state.selectedTimeSlot) {
            const timeSlotElem = document.querySelector(`.time-slot[data-time="${state.selectedTimeSlot.time}"]`);
            if (timeSlotElem && !timeSlotElem.classList.contains('unavailable')) {
                timeSlotElem.click();
            } else {
                state.selectedTimeSlot = null;
            }
        }
    }
    
    /**
     * Generate mock time slots for testing
     */
    function generateMockTimeSlots(dateString) {
        const slots = [];
        const date = new Date(dateString);
        const now = new Date();
        const isToday = date.toDateString() === now.toDateString();
        const currentHour = now.getHours();
        
        // Generate time slots from 8:00 to 17:00
        for (let hour = 8; hour <= 17; hour++) {
            // Skip lunch hour
            if (hour === 12) continue;
            
            // For each hour, create slots at :00 and :30
            ['00', '30'].forEach(minute => {
                // If it's today, don't show past time slots
                if (isToday && hour < currentHour) return;
                
                const time = `${hour.toString().padStart(2, '0')}:${minute}`;
                
                // Randomly mark some slots as unavailable
                const available = Math.random() > 0.3;
                
                slots.push({
                    time,
                    available,
                    duration: Math.random() > 0.5 ? 30 : 45 // Random duration for demonstration
                });
            });
        }
        
        return slots;
    }
    
    /**
     * Update the appointment summary in step 3
     */
    function updateAppointmentSummary() {
        if (!state.selectedDoctor || !state.selectedTimeSlot) return;
        
        const doctorInfo = document.getElementById('summary-doctor-info');
        const summaryDate = document.getElementById('summary-date');
        const summaryTime = document.getElementById('summary-time');
        const summaryType = document.getElementById('summary-type');
        const summaryDuration = document.getElementById('summary-duration');
        const datePicker = document.getElementById('appointment-date');
        const typeSelect = document.getElementById('appointment-type');
        
        if (!doctorInfo || !summaryDate || !summaryTime || !summaryType || !summaryDuration || !datePicker || !typeSelect) return;
        
        // Format the date
        const dateObj = new Date(datePicker.value);
        const formattedDate = dateObj.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' });
        
        // Get appointment type text
        const appointmentType = typeSelect.value;
        const appointmentTypeText = state.appointmentTypes[appointmentType] || appointmentType;
        
        // Update the summary
        doctorInfo.innerHTML = `
            <div class="doctor-card-simple">
                <img src="${state.selectedDoctor.avatar}" alt="${state.selectedDoctor.name}">
                <div>
                    <h5>${state.selectedDoctor.name}</h5>
                    <p>${state.selectedDoctor.specialty} · ${state.selectedDoctor.hospital}</p>
                </div>
            </div>
        `;
        
        summaryDate.textContent = formattedDate;
        summaryTime.textContent = state.selectedTimeSlot.time;
        summaryType.textContent = appointmentTypeText;
        summaryDuration.textContent = `${state.selectedTimeSlot.duration} 分钟`;
    }
    
    /**
     * Submit the appointment
     */
    function submitAppointment() {
        const notes = document.getElementById('appointment-notes')?.value || '';
        const location = document.getElementById('appointment-location')?.value || '线上问诊';
        const appointmentType = document.getElementById('appointment-type')?.value || 'REGULAR';
        const appointmentDate = document.getElementById('appointment-date')?.value || '';
        
        if (!state.selectedDoctor || !state.selectedTimeSlot || !appointmentDate) {
            showValidationError('请填写完整预约信息');
            return;
        }
        
        // Prepare appointment data
        const appointmentData = {
            doctorId: state.selectedDoctor.id,
            doctorName: state.selectedDoctor.name,
            doctorSpecialty: state.selectedDoctor.specialty,
            doctorAvatar: state.selectedDoctor.avatar,
            date: appointmentDate,
            time: state.selectedTimeSlot.time,
            duration: state.selectedTimeSlot.duration,
            type: appointmentType,
            notes: notes,
            location: location,
            status: 'PENDING' // New appointments are pending until confirmed by doctor
        };
        
        // In a real app, this would be an API call
        // For now, we'll simulate a successful response
        console.log('Submitting appointment:', appointmentData);
        
        // Simulate API delay
        const modal = document.getElementById('appointment-modal');
        const modalBody = document.getElementById('appointment-modal-body');
        
        if (!modal || !modalBody) return;
        
        // Show loading state
        modalBody.innerHTML = `
            <div class="loading-spinner">
                <i class="fas fa-spinner fa-spin"></i>
                <span>正在提交预约请求...</span>
            </div>
        `;
        
        // Simulate API delay
        setTimeout(() => {
            // Show success message
            modalBody.innerHTML = `
                <div class="success-message">
                    <i class="fas fa-check-circle"></i>
                    <h3>预约申请已提交</h3>
                    <p>您的预约申请已成功提交，请等待医生确认。</p>
                    <p>确认后，我们将通过短信和系统通知通知您。</p>
                    <div class="appointment-reference">
                        <strong>预约参考号</strong>
                        <code>${generateReferenceNumber()}</code>
                    </div>
                    <button id="close-success" class="btn btn-primary">完成</button>
                </div>
            `;
            
            // Add event listener to close button
            const closeBtn = document.getElementById('close-success');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    if (typeof AppointmentManager !== 'undefined' && AppointmentManager.hideModal) {
                        AppointmentManager.hideModal();
                        
                        // Refresh appointments data
                        if (AppointmentManager.refreshAppointments) {
                            AppointmentManager.refreshAppointments();
                        }
                    }
                });
            }
        }, 1500);
    }
    
    /**
     * Generate a random reference number for the appointment
     */
    function generateReferenceNumber() {
        const timestamp = new Date().getTime().toString().slice(-8);
        const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
        return `APT-${timestamp}-${random}`;
    }
    
    /**
     * Render the appointment view form
     */
    function renderViewForm(modalBody, appointment) {
        state.currentAppointment = appointment;
        state.formMode = 'view';
        
        modalBody.innerHTML = `
            <div class="appointment-view">
                <div class="appointment-status">
                    <span class="status-badge large ${appointment.status.toLowerCase()}">${getStatusText(appointment.status)}</span>
                </div>
                
                <div class="appointment-view-section">
                    <h4>预约详情</h4>
                    <div class="detail-grid">
                        <div class="detail-row">
                            <span class="detail-label">预约日期</span>
                            <span class="detail-value">${formatAppointmentDate(appointment.date)}</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">预约时间</span>
                            <span class="detail-value">${formatAppointmentTime(appointment.time, appointment.duration)}</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">预约类型</span>
                            <span class="detail-value">${getAppointmentTypeText(appointment.type)}</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">预约地点</span>
                            <span class="detail-value">${appointment.location}</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">预约号</span>
                            <span class="detail-value">${appointment.id}</span>
                        </div>
                    </div>
                </div>
                
                <div class="appointment-view-section">
                    <h4>医生信息</h4>
                    <div class="doctor-card-simple">
                        <img src="${appointment.doctorAvatar}" alt="${appointment.doctorName}">
                        <div>
                            <h5>${appointment.doctorName}</h5>
                            <p>${appointment.doctorSpecialty}</p>
                        </div>
                    </div>
                </div>
                
                ${appointment.notes ? `
                <div class="appointment-view-section">
                    <h4>预约原因 / 症状描述</h4>
                    <div class="appointment-notes">${appointment.notes}</div>
                </div>
                ` : ''}
                
                <div class="appointment-view-actions">
                    ${appointment.status === 'PENDING' || appointment.status === 'CONFIRMED' ? `
                    <button id="cancel-appointment" class="btn btn-outline-danger">
                        <i class="fas fa-times"></i> 取消预约
                    </button>
                    ` : ''}
                    
                    ${appointment.status === 'CONFIRMED' ? `
                    <button id="start-consultation" class="btn btn-primary">
                        <i class="fas fa-video"></i> 开始问诊
                    </button>
                    ` : ''}
                    
                    ${appointment.status === 'COMPLETED' ? `
                    <button id="view-record" class="btn btn-outline">
                        <i class="fas fa-file-medical"></i> 查看记录
                    </button>
                    ` : ''}
                </div>
            </div>
        `;
        
        // Add event listeners to the action buttons
        const cancelBtn = document.getElementById('cancel-appointment');
        const startConsultationBtn = document.getElementById('start-consultation');
        const viewRecordBtn = document.getElementById('view-record');
        
        if (cancelBtn) {
            cancelBtn.addEventListener('click', () => {
                if (typeof AppointmentManager !== 'undefined' && AppointmentManager.cancelAppointment) {
                    AppointmentManager.cancelAppointment(appointment.id);
                }
            });
        }
        
        if (startConsultationBtn) {
            startConsultationBtn.addEventListener('click', () => {
                if (typeof AppointmentManager !== 'undefined' && AppointmentManager.startConsultation) {
                    AppointmentManager.startConsultation(appointment.id);
                }
            });
        }
        
        if (viewRecordBtn) {
            viewRecordBtn.addEventListener('click', () => {
                if (typeof AppointmentManager !== 'undefined' && AppointmentManager.viewRecord) {
                    AppointmentManager.viewRecord(appointment.id);
                }
            });
        }
    }
    
    /**
     * Format the appointment date
     */
    function formatAppointmentDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', { 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric', 
            weekday: 'long' 
        });
    }
    
    /**
     * Format the appointment time
     */
    function formatAppointmentTime(time, duration) {
        const [hours, minutes] = time.split(':');
        const startTime = `${hours}:${minutes}`;
        
        // Calculate end time
        const endTime = calculateEndTime(time, duration);
        
        return `${startTime} - ${endTime}`;
    }
    
    /**
     * Calculate the end time based on start time and duration
     */
    function calculateEndTime(startTime, durationMinutes) {
        const [hours, minutes] = startTime.split(':').map(Number);
        
        const startDate = new Date();
        startDate.setHours(hours, minutes, 0, 0);
        
        const endDate = new Date(startDate.getTime() + durationMinutes * 60000);
        
        return endDate.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
    }
    
    /**
     * Get the display text for an appointment status
     */
    function getStatusText(status) {
        const statusMap = {
            'PENDING': '待确认',
            'CONFIRMED': '已确认',
            'COMPLETED': '已完成',
            'CANCELLED': '已取消',
            'RESCHEDULED': '已改期'
        };
        
        return statusMap[status] || status;
    }
    
    /**
     * Get the display text for an appointment type
     */
    function getAppointmentTypeText(type) {
        const typeMap = {
            'REGULAR': '常规问诊',
            'FOLLOW_UP': '复诊',
            'CONSULTATION': '专家会诊',
            'PHYSICAL': '体检预约',
            'EMERGENCY': '紧急预约'
        };
        
        return typeMap[type] || type;
    }
    
    /**
     * Get mock doctors for development
     */
    function getMockDoctors() {
        return [
            {
                id: 101,
                name: "李医生",
                specialty: "内科",
                hospital: "健康医院",
                avatar: "/images/doctor1.jpg",
                rating: 4.9,
                patientCount: 328,
                experience: "10年"
            },
            {
                id: 102,
                name: "王医生",
                specialty: "心脏科",
                hospital: "健康医院",
                avatar: "/images/doctor2.jpg",
                rating: 4.8,
                patientCount: 256,
                experience: "15年"
            },
            {
                id: 103,
                name: "张医生",
                specialty: "神经科",
                hospital: "健康医院",
                avatar: "/images/doctor3.jpg",
                rating: 4.7,
                patientCount: 198,
                experience: "8年"
            },
            {
                id: 104,
                name: "刘医生",
                specialty: "骨科",
                hospital: "健康医院",
                avatar: "/images/doctor4.jpg",
                rating: 4.6,
                patientCount: 213,
                experience: "12年"
            },
            {
                id: 105,
                name: "陈医生",
                specialty: "妇产科",
                hospital: "健康医院",
                avatar: "/images/doctor5.jpg",
                rating: 4.9,
                patientCount: 301,
                experience: "12年"
            },
            {
                id: 106,
                name: "赵医生",
                specialty: "儿科",
                hospital: "健康医院",
                avatar: "/images/doctor6.jpg",
                rating: 4.7,
                patientCount: 275,
                experience: "9年"
            }
        ];
    }
    
    // Event binding utils
    function bindDateChangeEvent() {
        const datePicker = document.getElementById('appointment-date');
        if (datePicker) {
            datePicker.addEventListener('change', loadTimeSlots);
        }
    }
    
    // Initialize the form module
    function init() {
        // Add event listeners for date selection and time slots
        document.addEventListener('shown.bs.modal', function (event) {
            if (event.target.id === 'appointment-modal') {
                bindDateChangeEvent();
                
                // If we're on step 2, load time slots
                if (state.currentStep === 2) {
                    loadTimeSlots();
                }
            }
        });
    }
    
    // Public API
    return {
        init: init,
        renderCreateForm: renderCreateForm,
        renderViewForm: renderViewForm,
        getMockDoctors: getMockDoctors
    };
})(); 